# -*- coding: utf-8 -*-

from mitmproxy.options import Options
from mitmproxy import http, ctx
from mitmproxy.connection import Server
from mitmproxy.coretypes.multidict import KT,VT
from mitmproxy.addons.proxyserver import Proxyserver
from mitmproxy.tools.dump import DumpMaster
import asyncio
from collections.abc import Sequence
import json
import logging
from AddonBase import AddonBase

class Addon(AddonBase):
    def __init__(self):
        super().__init__()

    def request(self, flow: http.HTTPFlow):
        print("二次代理",flow.request.url)

    def response(self, flow: http.HTTPFlow):
        # print("响应", flow.response.get_state())
        pass

def MitmProxyStart():
    async def _main():
        # 初始设置代理模式 默认：regular
        # mode: Sequence[str] = ["upstream:http://localhost:7889"]
        # options = Options(listen_host='localhost', listen_port=8889, mode=mode)
        options = Options(listen_host='localhost', listen_port=8888)
        options.add_option("connection_strategy", str, "lazy", "")
        options.add_option("upstream_cert", bool, False, "")
        options.add_option("ssl_insecure", bool, True, "")
        # EventLog verbosity. Default: info  Choices: error, warn, info, alert, debug
        #事件日志 默认为 info
        options.add_option("console_eventlog_verbosity",str,"error","")
        # Log verbosity.. Default: info  Choices: error, warn, info, alert, debug
        options.add_option("termlog_verbosity", str, "error", "")
        # 替换代理模式
        # mode: Sequence[str] = ["upstream:http://localhost:7889"]
        # mode_option = {'mode': mode}
        # options.update(**mode_option)
        m = DumpMaster(options=options)
        m.server = Proxyserver()
        addons = Addon()
        m.addons.add(addons)
        await m.run()
    try:
        asyncio.run(_main())
    except KeyboardInterrupt:
        pass

if __name__ == '__main__':

    MitmProxyStart()

    '''
    pyinstaller pymitmdump\mitmdumpStartApi.py --distpath pymitmdumpstartdist --add-data "pymitmdump\mitmdump_executable;mitmdump_executable" --add-data "pymitmdump\mitmdumpUrlSaver.py;."
    pyinstaller pymitmdump\mitmdumpOtherApi.py --distpath pymitmdumpotherdist
    '''
